package api;

import dao.User;
import dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取到用户名和用户密码
        req.setCharacterEncoding("gb2312");
        String username=req.getParameter("Nusername");
        String Npassword1=req.getParameter("Npassword1");
        String Npassword2=req.getParameter("Npassword2");
        if(username==null || Npassword1==null || Npassword2==null || username.equals("") || Npassword1.equals("") ||Npassword2.equals(""))
        {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("未输入用户名或者密码");
            return;
        }
        if(! Npassword1.equals(Npassword2))
        {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("两次密码输入不一致");
            return;
        }
        //2.和数据库验证
        UserDao userDao=new UserDao();//创建连接
       //在数据库中查找
        if(userDao.getUserByName(username)!=null)//用户存在
        {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户已存在无需注册，请登入");
            return;
        }
        User user=new User();
        user.setUsername(username);
        user.setPassword(Npassword1);
        userDao.insert(user);
        //都ok,创建会话
        HttpSession session = req.getSession(true);//存在查询，不存在创建，生成键值对
        //将用户的信息保存到
        session.setAttribute("user", user);
        //跳转页面
        resp.setContentType("text/html;charset=utf8");
        resp.sendRedirect("login.html");

    }

}
